<template>
  <basic-container>
    <avue-crud
      :option="option"
      :data="data"
      ref="crud"
      v-model="form"
      :permission="permissionList"
      @row-del="rowDel"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @on-load="onLoad"
      @keydown.native="keydown($event)"
    >
      <template slot="menuLeft">
        <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          v-if="permission.role_delete"
          plain
          @click="handleDelete"
        >删 除</el-button>
        <el-button size="small" icon="el-icon-delete" @click="handleRole" plain>权限设置</el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button
          type="text"
          icon="el-icon-office-building"
          size="small"
          @click.stop="handleEdit(scope.row,scope.index)"
        >城市权限</el-button>
        <el-button
          type="text"
          icon="el-icon-box"
          size="small"
          @click.stop="handleHouseEdit(scope.row,scope.index)"
        >仓库权限</el-button>
      </template>
    </avue-crud>
    <el-dialog title="角色配置" :visible.sync="box" width="20%">
      <el-tree
        :data="list"
        show-checkbox
        node-key="id"
        ref="tree"
        :default-checked-keys="defaultObj"
        :props="props"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="box = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="请选择所属部门" :visible.sync="handleEditFlag" width="50%">
      <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
      <el-tree
        :data="deptlist"
        show-checkbox
        ref="depttree"
        default-expand-all
        highlight-current
        node-key="id"
        :default-checked-keys="defaultdeptObj"
        :filter-node-method="filterNode"
        :props="deptprops"
      ></el-tree>
      <div style="display: flex;justify-content: flex-end;">
        <el-button @click="handleEditFlag = false">取 消</el-button>
        <el-button type="primary" @click="deptsubmit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="请选择所属仓库" :visible.sync="handleHouseEditFlag" width="50%">
      <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
      <el-tree
        :data="houselist"
        show-checkbox
        ref="housetree"
        default-expand-all
        highlight-current
        node-key="warehourceId"
        :default-checked-keys="defaultdeptObj"
        :filter-node-method="filterhouseNode"
        :props="houseprops"
      ></el-tree>
      <div style="display: flex;justify-content: flex-end;">
        <el-button @click="handleHouseEditFlag = false">取 消</el-button>
        <el-button type="primary" @click="deptHousesubmit">确 定</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  add,
  getList,
  getRole,
  getRoleTree,
  grant,
  grantTree,
  remove,
  update,
} from "@/api/system/role";
import {
  updateRoleDept,
  getCityJurisdiction,
  getWareHouseGroupByDeptId, // 获取仓库权限数据
  saveOrUpdateRoleWarehouse, // 保存/更新仓库权限
} from "@/api/system/dept";
import { mapGetters } from "vuex";
import website from "@/config/website";

export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入角色名称"));
      } else {
        this.form.roleName = value.replace(/\s+/g, "");
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入角色别名"));
      } else {
        this.form.roleAlias = value.replace(/\s+/g, "");
        callback();
      }
    };
    return {
      filterText: "", // 关键字过滤
      handleEditFlag: false, // 城市权限标记
      handleHouseEditFlag: false, // 城市权限标记
      getCityJurisdictionQuery: {
        // 城市权限请求
        roleId: "",
      },
      updateRoleDeptQuery: {
        roleId: "",
        deptIds: [],
        mainWarehouseIds: [],
      },
      saveOrUpdateRoleWareQuery: { // 保存/更新仓库权限
        roleId: "",
        warehouseIds: [],
      },
      deptlist: [], // 所属部门列表
      houselist: [ ],// 仓库列表
      form: {},
      box: false,
      props: {
        label: "title",
        value: "key",
      },
      // 该数组是选中的节点(半选的节点和全选的节点全都存储在这个数组)
      multipleSelection: [],
      deptprops: {
        label: "deptName",
        value: "id",
      }, // 传入的值
      houseprops: {
        label: "warehourceName",
        value: "warehourceId"
      }, // 传仓库入的值
      list: [],
      defaultObj: [],
      defaultdeptObj: [],
      defaulthouseObj: [],
      selectionList: [],
      query: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        // menuWidth: 250,
        align: 'left',
        tip: false,
        tree: true,
        border: true,
        index: true,
        selection: true,
        columnBtn: false, // 列显隐按钮
        refreshBtn: false, // 刷新按钮
        searchBtn: false, // 搜索显隐按钮（当 column 中有搜索的属性，或则 searchsolt 为 true 时自定义搜索启动起作用）
        viewBtn: true,
        dialogWidth: 300,
        dialogHeight: 400,
        column: [
          {
            label: "角色名称",
            prop: "roleName",
            search: true,
            span: 24,
            rules: [
              {
                required: true,
                validator: validatePass,
                trigger: "change",
              },
            ],
          },
          {
            label: "所属租户",
            prop: "tenantId",
            type: "tree",
            dicUrl: "/api/xmbz-system/tenant/select",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: website.tenantMode,
            span: 24,
            props: {
              label: "tenantName",
              value: "tenantId",
              children: "children",
            },
            // hide: !website.tenantMode,
            // search: website.tenantMode,
            hide: true,
            search: false,
            rules: [
              {
                required: true,
                message: "请输入所属租户",
                trigger: "click",
              },
            ],
          },
          {
            label: "角色别名",
            prop: "roleAlias",
            search: true,
            span: 24,
            rules: [
              {
                required: true,
                validator: validatePass2,
                trigger: "change",
              },
            ],
          },
          {
            label: "上级角色",
            prop: "parentId",
            dicData: [],
            type: "tree",
            hide: true,
            span: 24,
            props: {
              label: "title",
            },
            rules: [
              {
                required: false,
                message: "请选择上级角色",
                trigger: "click",
              },
            ],
          },
          {
            label: "角色排序",
            prop: "sort",
            type: "number",
            span: 24,
            rules: [
              {
                required: true,
                message: "请输入角色排序",
                trigger: "blur",
              },
            ],
          },
        ],
      },
      data: [],
      getWareHouseGroupByDeptId: {
        roleId: ''
      },
    };
  },
  created() {
    window.addEventListener("keydown",this.keyupEnter);
  },
  watch: {
    filterText(val) {
      this.$refs.depttree.filter(val);
    },
    'box'() {
      if(this.box) {
        window.removeEventListener("keydown",this.keyupEnter);
      } else {
        window.addEventListener("keydown",this.keyupEnter);
      }
    },
    'handleEditFlag'() {
      if(this.handleEditFlag) {
        window.removeEventListener("keydown",this.keyupEnter);
      } else {
        window.addEventListener("keydown",this.keyupEnter);
      }
    },
    'handleHouseEditFlag'() {
      if(this.handleHouseEditFlag) {
        window.removeEventListener("keydown",this.keyupEnter);
      } else {
        window.addEventListener("keydown",this.keyupEnter);
      }
    }
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.role_add, false),
        viewBtn: this.vaildData(this.permission.role_view, false),
        delBtn: this.vaildData(this.permission.role_delete, false),
        editBtn: this.vaildData(this.permission.role_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  methods: {
    submit() {
      const menuLIst = this.$refs.tree.getCheckedKeys().join(",");
      grant(this.ids, menuLIst).then(() => {
        this.box = false;
        this.$message({
          type: "success",
          message: "操作成功!",
        });
        this.onLoad(this.page);
      });
    },
    rowSave(row, loading, done) {
      if (this.form.sort >= 0) {
        add(row).then(
          () => {
            loading();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
          },
          (error) => {
            done();
            console.log(error);
          }
        );
      } else {
        this.$message.warning("角色排序不能为负数，请重新编辑");
        done();
      }
    },
    rowUpdate(row, index, loading, done) {
      // 新建、编辑的时候的保存
      if (this.form.sort >= 0) {
        update(row).then(
          () => {
            this.onLoad(this.page);
            loading();
            this.$message({
              type: "success",
              message: "操作成功!",
            });
          },
          (error) => {
            done();
            console.log(error);
          }
        );
      } else {
        this.$message.warning("角色排序不能为负数，请重新编辑");
        done();
      }
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params) {
      this.query = params;
      this.onLoad(this.page, params);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    handleRole() {
      if (this.selectionList.length <= 0) {
        this.$message.warning("请至少选择一条数据");
        return;
      } else if (this.selectionList.length > 3) {
        this.$message.warning("至多只能选择三条数据");
        return;
      }
      this.defaultObj = [];
      grantTree()
        .then((res) => {
          this.list = res.data.data;
          this.list.forEach(item => {
            if(item.children !== undefined) {
              item.children.forEach(childitem => {
                if(childitem.title == '同步订单失败') {
                  if(this.ids == 1) {
                    childitem.disabled = false;
                  } else {
                    childitem.disabled = true;
                  }
                }
              })
            }
          })
          return getRole(this.ids);
        })
        .then((res) => {
          this.defaultObj = res.data.data;
          this.box = true;
          let sunArray = [];
          let ittemmArray = [];
          this.list.forEach(item => {
            let defalutArray = [];
            this.defaultObj.forEach(defaultitem => {
              if(item.id == defaultitem) {
                item.children.forEach(childitem => {
                  this.defaultObj.forEach(sunitem => {
                    if(childitem.id == sunitem) {
                      defalutArray.push(sunitem)
                      sunArray.push(sunitem)
                      if(childitem.children !== undefined) {
                        childitem.children.forEach(thirditem => {
                          this.defaultObj.forEach(thirddefitem => {
                            if(thirditem.id == thirddefitem) {
                              sunArray.push(thirddefitem);
                              if(thirditem.children !== undefined) {
                                thirditem.children.forEach(fouritem => {
                                  this.defaultObj.forEach(fourdefitem => {
                                    if(fouritem.id == fourdefitem) sunArray.push(fourdefitem);
                                  })
                                })
                                
                              }
                            }
                          })
                        })
                      }
                    }
                  })
                })
                if(defalutArray.length == item.children.length) {
                  sunArray.push(defaultitem);
                };
              }
            })
          })
          this.defaultObj.forEach(iitem => {
            if(sunArray.indexOf(iitem) == -1) {
              sunArray.push(iitem);
            }
          })
          sunArray.sort((a,b)=>{return a-b});
          this.defaultObj = sunArray;
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        this.data = res.data.data;
        getRoleTree().then((res) => {
          const data = res.data.data;
          const index = this.$refs.crud.findColumnIndex("parentId");
          this.option.column[index].dicData = data;
        });
      });
    },
    handleEdit(row) {
      // 城市权限编辑
      this.handleEditFlag = true; // 城市权限Flag
      this.getCityJurisdictionQuery.roleId = row.id;
      getCityJurisdiction(this.getCityJurisdictionQuery).then((res) => {
        this.deptlist = res.data.data;
        this.defaultdeptObj = res.data.data;
        let deptarr = [];
        // console.log("this.$refs.depttree.getCheckedNodes()",res.data.data);
        res.data.data.forEach((item) => {
          if (item.isSelect == 1) {
            deptarr.push(item.id);
            item.children.forEach((itemdept) => {
              if (itemdept.isSelect == 1) {
                deptarr.push(itemdept.id);
              }
            });
          } else {
            item.children.forEach((itemdept) => {
              if (itemdept.children !== undefined) {
                itemdept.children.forEach((itemhouse) => {
                  if (itemhouse.isSelect == 1 && deptarr.indexOf(itemhouse.id) == -1) {
                    deptarr.push(itemhouse.id);
                  }
                });
                if(itemdept.children.length > 0) {
                  let areaArr = []
                  itemdept.children.forEach(areaitem => {
                    if(areaitem.isSelect == 1) areaArr.push(areaitem.id)
                  })
                  // console.log('areaArr',areaArr)
                  if(areaArr.length == itemdept.children.length && itemdept.isSelect == 1 && deptarr.indexOf(itemdept.id) == -1) deptarr.push(itemdept.id);
                }
                if(itemdept.children.length == 0) {
                    if (itemdept.isSelect == 1) {
                    deptarr.push(itemdept.id);
                    // console.log(itemdept)
                  }
                }
              }
            });
          }
        });
        // console.log('deptarr',deptarr)
        this.$nextTick(() => {
          this.$refs.depttree.setCheckedKeys(deptarr); //获取已经设置的资源后渲染
        });
      });
    },
    // 城市过滤
    filterNode: function (value, data) {
      if (!value) return true;
      return data.deptName.indexOf(value) !== -1;
    },
    deptsubmit() {
      if (this.$refs.depttree.getCheckedNodes().length > 0) {
        let res = this.$refs.depttree.getCheckedNodes()
        let mainWarehouseIds = [];
        let arr = [];
        let deptIds = []
        this.deptlist.forEach((item) => {
          item.children.forEach((cityitem) => {
            // console.log('arr',cityitem)
            arr.push(cityitem.id)
          });
        });
        res.forEach((item) => {
          if (item.parentId !== 1) {
            mainWarehouseIds.push(item.id);
            arr.forEach(cityitem => {
              if(cityitem == item.parentId && deptIds.indexOf(cityitem) == -1) {
                deptIds.push(cityitem)
              }
            })
          }
          if(item.parentId == 1) {
            deptIds.push(item.id)
          }
        });
        this.updateRoleDeptQuery.deptIds = deptIds;
        this.updateRoleDeptQuery.mainWarehouseIds = mainWarehouseIds;
        this.updateRoleDeptQuery.roleId = this.getCityJurisdictionQuery.roleId;
        if (this.updateRoleDeptQuery.mainWarehouseIds.indexOf(1) > -1) {
          this.updateRoleDeptQuery.mainWarehouseIds = this.updateRoleDeptQuery.mainWarehouseIds.slice(1,mainWarehouseIds.length);
          updateRoleDept(this.updateRoleDeptQuery).then((res) => {
            // console.log('请求成功',res.data)
            if (res.data.code == 200) {
              this.onLoad(this.page);
              this.$message({
                message: "设置成功",
                type: "success",
              });
              this.handleEditFlag = false; // 城市权限Flag
              window.location.reload();
            }
          });
        } else {
          updateRoleDept(this.updateRoleDeptQuery).then((res) => {
            // console.log('请求成功',res.data)
            if (res.data.code == 200) {
              this.onLoad(this.page);
              this.$message({
                message: "设置成功",
                type: "success",
              });
              this.handleEditFlag = false; // 城市权限Flag
              window.location.reload();
            }
          });
        }
      } else {
        this.$message.warning("请选择至少一条数据");
      }
    },
    // 仓库过滤
    filterhouseNode: function (value, data) {
      if (!value) return true;
      return data.title.indexOf(value) !== -1;
    },
    handleHouseEdit(row) {
      this.saveOrUpdateRoleWareQuery.roleId = row.id; // 仓库权限请求roleId
      // this.getWareHouseGroupByDeptId.roleId = row.id; // 仓库权限请求roleId
      // 仓库权限编辑
      this.handleHouseEditFlag = true; // 城市权限Flag
      getWareHouseGroupByDeptId(row.id).then(res => {
        let result = res.data.data;
        this.defaulthouseObj = result;
        let housearr = [];
        result.forEach((item) => {
          item.warehourceName = item.name
          item.disabled = true;
          item.children.forEach(houseitem => {
            houseitem.disabled = true;
            houseitem.warehourceName = houseitem.name;
            if (houseitem.children !== undefined) {
              houseitem.children.forEach((itemhouse) => {
                itemhouse.disabled = false;
                // console.log('houseitem',houseitem)
                if (itemhouse.isSelect == 1) {
                  housearr.push(itemhouse.warehourceId);
                  // console.log('houseitem',itemhouse)
                }
              });
            }
          })
        });
        this.houselist = result;
        this.defaulthouseObj = this.houselist;
        this.$nextTick(() => {
          this.$refs.housetree.setCheckedKeys(housearr); //获取已经设置的资源后渲染
        });
      })
    },
    // 仓库权限设置
    deptHousesubmit() {
      if (this.$refs.housetree.getCheckedNodes().length > 0) {
        let res = this.$refs.housetree.getCheckedNodes();
        let arr = [];
        res.forEach((item) => {
          if(item.warehourceId !== undefined) arr.push(item.warehourceId)
        });
        this.saveOrUpdateRoleWareQuery.warehouseIds = arr
        saveOrUpdateRoleWarehouse(this.saveOrUpdateRoleWareQuery).then((res) => {
          if (res.data.code == 200) {
            this.onLoad(this.page);
            this.$message({
              message: "设置成功",
              type: "success",
            });
            this.handleHouseEditFlag = false; // 城市权限Flag
          }
        });
      } else {
        this.$message.warning("请选择至少一条数据");
      }
    },
    // 禁止输入空格
    keydown(event){
      if(event.keyCode == 32){
        event.returnValue = false
      }
    },
    // 回车事件
    keyupEnter(){
      let dialogArray = document.getElementsByClassName('avue-crud__dialog');
      let displayArray = [];
      for(let i = 0;i < dialogArray.length;i++) {
        if(dialogArray[i].style.display == '') displayArray.push(false);
      }
      if(displayArray.indexOf(false) == -1) {
        if(window.event.keyCode == 13 ){
          let InputArrays = document.getElementsByClassName('el-input__inner')
          let roleName = '';
          let roleAlias = '';
          for(let i = 0;i < InputArrays.length;i++) {
            if (InputArrays[i].placeholder == '角色名称') roleName = InputArrays[i].value
            if (InputArrays[i].placeholder == '角色别名') roleAlias = InputArrays[i].value
          }
          this.query.roleName = roleName;
          this.query.roleAlias = roleAlias;
          this.onLoad(this.page, this.query);
          event.returnValue = false;
        }
      }
    },
  },
  destroyed() {
    window.removeEventListener("keydown",this.keyupEnter);
  },
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() {
    window.addEventListener("keydown",this.keyupEnter);
  },
  deactivated() {
    window.removeEventListener("keydown",this.keyupEnter);
  }
};
</script>

<style>
</style>
